<template>
  <cu-layout :bgStyle="{ color: actBgColor }" :navProp="{ placeholder: true, isOpacity: false }">
    <view :class="[`${prefixCls}-bring-activity-container`]">
      <view class="activity-header">
        <view class="activity-title uv-line-2">{{ actDetail.title }}</view>
        <view class="activity-time" v-if="actDetail.time_s">
          <text>{{ `${actDetail.time_s || ''} - ${actDetail.time_e || ''}` }}</text>
        </view>
      </view>
      <view class="activity-body">
        <!-- 活动介绍 -->
        <ActivityCard :cardInfo="rewardCard" v-if="actDetail.reward_list && actDetail.reward_list.length">
          <!-- 活动奖励 -->
          <RewardCard :rewardList="actDetail.reward_list" />
        </ActivityCard>

        <!-- 参与步骤 -->
        <ActivityCard :cardInfo="stepCard">
          <!-- 步骤 -->
          <StepCard />
        </ActivityCard>
      </view>

      <!-- 参与活动 -->
      <view class="activity-footer" :style="{ paddingBottom: `${buttomSafeArea}px` }">
        <uv-button size="large" shape="circle" color="#fb6338" :disabled="joinDisabled" :loading="joinLoading" @click="joinActivity" text="参与活动" />
      </view>

      <!-- 活动规则 -->
      <view class="rule-tips" :style="{ top: `${$Platform.device.safeAreaInsets.top + 44 + 20}px` }" @click="openRulePopup">活动规则</view>
      <ActivityRule ref="activityRulePopup" :ruleInfo="actRule" />

      <!-- 分享海报 -->
      <cu-poster ref="canvasPoster" :posterImage="posterInfo.poster_pic" :posterJson="activityPosterConfig" :shareInfo="onSharePageConfig" buttonColor="#fb6338" />
    </view>
  </cu-layout>
</template>

<script>
import share from '@/mixins/share'
import { mapGetters } from 'vuex'
import activityPoster from './activityPosterConfig.js'
import ActivityCard from './components/activity-card.vue'
import ActivityRule from './components/activity-rule.vue'
import RewardCard from './components/reward-card.vue'
import StepCard from './components/step-card.vue'

import { getBringActivityConfig, getBringActivityInviteId, getBringActivityPoster, getBringActivityRule, getBringActivityScene, verifyBringActivityQualification } from './api'
export default {
  name: 'bringActivityIndex',
  components: { ActivityRule, ActivityCard, RewardCard, StepCard },
  mixins: [share],
  props: {},
  data() {
    return {
      isSharePYQscene: !1,
      actId: '', // 活动id
      actInviteUId: '', // 邀请人id（当前用户id）通过接口获取
      actDetail: {},
      isEligible: !1, // 是否有资格
      actRule: {
        title: '活动规则',
        content: '',
      },
      posterInfo: {
        poster_pic: '',
      },
      rewardCard: { title: '奖励介绍', description: '每成功邀请一位好友入住苏享家，根据好友签约时长获得以下 奖励之一' },
      stepCard: { title: '参与步骤', description: '' },

      joinLoading: !1, // 参与按钮是否loading
    }
  },
  // 侦听属性
  watch: {},
  // 计算属性
  computed: {
    ...mapGetters(['isLogin', 'userInfo']),
    safeBottomAreaInsets() {
      return `${this.$Platform.device.safeAreaInsets.bottom + 70}px`
    },
    actBgImage() {
      return `url(${this.actDetail?.bg_img_main || CDN('/customer/static/images/activity/bring_activity_index_bg@2x.jpg')}) no-repeat top center / contain`
    },
    actBgColor() {
      return this.actDetail?.bg_color_main || '#20a793'
    },
    onSharePageConfig() {
      return this.$Platform.share.getShareInfo(
        {
          title: this.actDetail?.old_share_head || '邀请好友一起住苏享家',
          image: this.actDetail?.old_share_img || CDN('/common/static/images/share/share_200x160.png'),
          desc: this.actDetail?.old_share_sub_head || '每成功邀请一位好友入住苏享家，可获得丰富的奖励哦！',
          params: {
            page: '/pages/subpackage/bringActivity/detail',
            /**
             * page传参方式
             * 1. 当前页面路由
             *          `/${getCurrentPages().pop().route}`
             * 2. 指定页面路由
             *          '/pages/subpackage/bringActivity/detail'
             */
            query: {
              actId: this.actId,
              actInviteUId: this.actInviteUId,
            },
            /**
             * query传参方式
             * 1. 通过params传参
             *          params: {
             *             actId: this.actId,
             *             actInviteUId: this.actInviteUId,
             *           }
             * 2. 通过query传参
             *             query: `actId=${this.actId}&actInviteUId=${this.actInviteUId}`
             */
          },
        },
        {
          title: '邀请好友一起住苏享家', // 标题
          image: this.actDetail?.bg_img || CDN('/common/static/images/share/poster_646x948.png'), // 主图
        },
      )
    },

    activityPosterConfig() {
      const activityPosterJson = activityPoster()
      return activityPosterJson
    },

    joinDisabled() {
      return !(this.isEligible && this.actInviteUId)
    },

    buttomSafeArea() {
      return this.$Platform.device.safeAreaInsets.bottom || 10
    },
  },
  // 监听页面加载，该钩子被调用时data,computed,function,watch,props,slots已设置完成
  async onLoad(options) {
    console.log('🚀 ~ onLoad bringActivity~ options:', options)
    // 朋友圈进入场景
    const { scene } = uni.getLaunchOptionsSync()
    const isSharePYQscene = [1154].includes(scene)
    this.isSharePYQscene = isSharePYQscene
    if (options.spm) {
      const { actId = '' } = this.$Platform.share.decryptSpm(options.spm)
      this.actId = actId
    } else if (options.scene) {
      const { actId = '' } = await this.getActQuery(options.scene)
      this.actId = actId
    } else this.actId = options.actId || ''

    await this.getPageData()
  },
  // 监听页面显示，页面每次出现在屏幕上都触发
  onShow() {},
  // 监听页面初次渲染完成，此时组件已挂载完成
  onReady() {},
  // 下拉刷新
  onPullDownRefresh() {},
  // 加载更多
  onReachBottom() {},

  created() {},
  mounted() {},
  destroyed() {},
  methods: {
    async getPageData() {
      if (!this.actId) return uni.$uv.toast('缺少活动参数！')

      // 获取活动详情
      this.getActDetail()
      if (!this.isSharePYQscene) {
        // 校验活动资格
        this.checkActQualification()
        // 获取邀请人id
        this.getActInviteId()
      }
      // 获取活动规则
      this.getActRule()
    },

    // 显示规则
    openRulePopup() {
      this.$refs.activityRulePopup.open()
    },

    // 参与活动
    async joinActivity() {
      console.log(this.shareInfo)
      await this.getActPoster()

      if (!this.posterInfo.poster_pic) return uni.$uv.toast('未获取到海报图！')

      this.$refs.canvasPoster.onOpenPoster()
    },

    // 获取海报图查询参数
    async getActQuery(scene) {
      const { errcode, data = {} } = await getBringActivityScene({ scene })
      if (errcode === 0) {
        return data?.params || {}
      }
    },

    // 获取活动详情
    async getActDetail() {
      const { errcode, data = {} } = await getBringActivityConfig({ act_id: this.actId })
      if (errcode === 0) {
        this.actDetail = data || {}
      }
    },

    // 校验用户是否有参加活动的资格
    async checkActQualification() {
      const { errcode } = await verifyBringActivityQualification({ act_id: this.actId })
      if (errcode === 0) {
        this.isEligible = !0
      }
    },

    // 获取邀请人的id
    async getActInviteId() {
      const { errcode, data = {} } = await getBringActivityInviteId({ act_id: this.actId })
      if (errcode === 0) {
        this.actInviteUId = data?.id || ''
      }
    },

    // 获取海报图
    async getActPoster() {
      const { errcode, data = {} } = await getBringActivityPoster({ invitation_id: this.actInviteUId })
      if (errcode === 0) {
        this.posterInfo.poster_pic = data?.poster_pic || ''
      }
    },

    // 获取活动规则
    async getActRule() {
      const { errcode, data = {} } = await getBringActivityRule({ act_id: this.actId })
      if (errcode === 0) {
        this.actRule.content = data?.rule || ''
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.#{prefixCls('bring-activity-container')} {
  position: relative;
  padding: 40rpx 30rpx 140rpx;
  padding-bottom: v-bind(safeBottomAreaInsets);
  background: v-bind(actBgImage);
  .activity-header {
    position: relative;
    margin-bottom: 560rpx;
    text-align: center;
    color: $uv-primary;
    .activity-title {
      width: 70%;
      margin: 56rpx auto 24rpx;
      font-size: 36rpx;
      font-weight: 600;
    }
    .activity-time {
      height: 40rpx;
      margin: 0 auto;
      text {
        padding: 4rpx 20rpx;
        font-size: 24rpx;
        line-height: 40rpx;
        border-radius: 20rpx;
        background: #fff;
      }
    }
  }

  .activity-footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    padding: 20rpx 30rpx;
    z-index: 99;
  }

  .rule-tips {
    width: 100rpx;
    height: 48rpx;
    position: fixed;
    right: 0;
    padding: 0 24rpx;
    background: rgba($color: #000000, $alpha: 0.5);
    border-top-left-radius: 240rpx;
    border-bottom-left-radius: 240rpx;
    line-height: 48rpx;
    font-size: 24rpx;
    color: #fff;
    z-index: 98;
  }
}
</style>
